package com.futvan.z.framework.core;
import java.net.InetSocketAddress;
import java.util.List;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;

/**
 * Canal客户端，用于监听数据库数据变化，配合阿里Canal框架使用
 */
public class DBListener {

    public static void main(String args[]) {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
                11111), "example", "", "");
        int batchSize = 1000;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            while (true) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId != -1 && size > 0) {
                    printEntry(message.getEntries());
                }
                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
        } finally {
            connector.disconnect();
        }
    }

    private static void printEntry(List<Entry> entrys) {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                continue;
            }

            try {
                //解析数据操作记录
                RowChange rowChage = RowChange.parseFrom(entry.getStoreValue());

                //获取数据操作类型 INSERT UPDATE DELETE
                EventType eventType = rowChage.getEventType();

                //打印数据操作记录
                z.Log(eventType+"|"+entry.getHeader().getSchemaName()+"|"+entry.getHeader().getTableName());
                for (RowData rowData : rowChage.getRowDatasList()) {
                    if (eventType == EventType.DELETE) {
                        printColumn(rowData.getBeforeColumnsList());
                    } else if (eventType == EventType.INSERT) {
                        printColumn(rowData.getAfterColumnsList());
                    } else {
                        System.out.println("-----------------------修改前-----------------------");
                        printColumn(rowData.getBeforeColumnsList());
                        System.out.println("-----------------------修改后-----------------------");
                        printColumn(rowData.getAfterColumnsList());
                    }
                }
            } catch (Exception e) {
                z.Error("解析Entry出错 , data:" + entry.toString());
            }
        }
    }

    private static void printColumn(List<Column> columns) {
        for (Column column : columns) {
            if(column.getUpdated()){
                z.Log("已变更|"+column.getName() + " : " + column.getValue());
            }else{
                z.Log("     |"+column.getName() + " : " + column.getValue());
            }
        }
    }

}
